
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Globalization;
using NHibernate;
namespace NCS_CS
{
    //.CultureInfo
    internal partial class FrmMethod : System.Windows.Forms.Form
    {
        string method1ele;
        //private void newMakemethod()
        //{
        //    int methodid = 0;
        //    string methodName = null;
        //    MyInputBox m = new MyInputBox("新方法的名称");
        //    m.ShowDialog();
        //    methodName = m.s;
        //    if (string.IsNullOrEmpty(methodName))
        //        return;
        //}

        public void xishuformat(object sender, System.Windows.Forms.ConvertEventArgs e)
        {
            //e.Value = e.Value.ToString("F7", CultureInfo.InvariantCulture)
            e.Value = string.Format("{0:F7}", e.Value);
            //return "";
        }
        public void EleChange(string elename)
        {
            if (ModMain.method1 == null)
                return;
            try
            {
                method1ele = elename;
                ModMain.cxishu = null;
                foreach (NCS.curveXishu cxishu1 in ModMain.method1.curveXishuList)
                {
                    if (cxishu1.ele == method1ele)
                    {
                        ModMain.cxishu = cxishu1;
                        break; 
                    }
                }
                if (ModMain.cxishu == null)
                {
                    ModMain.cxishu = new NCS.curveXishu();
                    ModMain.cxishu.x0 = 0;
                    ModMain.cxishu.x1 = 0;
                    ModMain.cxishu.ele = method1ele;
                    ModMain.cxishu.cishu = 1;
                    ModMain.cxishu.method = ModMain.method1;
                    ModMain.method1.curveXishuList.Add(ModMain.cxishu);
                    ModMain.getsession().Save(ModMain.cxishu);
                    ModMain.getsession().Flush();
                }
                System.Windows.Forms.Binding b = new System.Windows.Forms.Binding("Text", ModMain.cxishu, "x0", true);
                b.Format += xishuformat;
                this.txtx0.DataBindings.Clear();
                this.txtx0.DataBindings.Add(b);

                System.Windows.Forms.Binding b1 = new System.Windows.Forms.Binding("Text", ModMain.cxishu, "x1", true);
                b1.Format += xishuformat;
                this.txtx1.DataBindings.Clear();
                this.txtx1.DataBindings.Add(b1);

                this.Text_lineable.DataBindings.Clear();
                this.Text_lineable.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "LINExishu"));

                this.txtstderr.DataBindings.Clear();
                this.txtstderr.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "stderr"));
                this.Text_low_limit.DataBindings.Clear();
                this.Text_low_limit.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "cmin"));
                this.Text_up_limit.DataBindings.Clear();
                this.Text_up_limit.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "cmax"));
                //Me.Check1.DataBindings.Clear()
                //Me.Check1.DataBindings.Add(New System.Windows.Forms.Binding("Checked", Cxishu, "must00"))
                // object o1 = this.Check1;
                // object o2 = ModMain.cxishu;

                //ModMain.rebind(ref o1, "Checked", ref o2, "must00");
                this.Check_across00.DataBindings.Clear();
                this.Check_across00.DataBindings.Add(new System.Windows.Forms.Binding("Checked", ModMain.cxishu, "must00"));
                //o1 = this.txtbjsp;
                //ModMain.rebind(ref o1, "Text", ref o2, "bjsp");
                this.txtbjsp.DataBindings.Clear();
                this.txtbjsp.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "bjsp"));
                //o1 = this.txtpanju;
                //ModMain.rebind(ref o1, "Text", ref o2, "panju");
                this.txtpanju.DataBindings.Clear();
                this.txtpanju.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "panju"));
                //o1 = this.TextBoxR2;
                //ModMain.rebind(ref o1, "Text", ref o2, "r");
                this.TextBoxR2.DataBindings.Clear();
                this.TextBoxR2.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "r"));
                //Me.Check1.Checked 
                //x=session.CreateSQLQuery() 
                this.text_blank_area.DataBindings.Clear();
                this.text_blank_area.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "blankarea"));

                this.textBoxLN.DataBindings.Clear();
                this.textBoxLN.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "ln"));

                //this.textBoxHN.DataBindings.Clear();
                //this.textBoxHN.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.cxishu, "hn"));

                
                refreshCurvedata();
                //showCurrentCurve()
                //Mcurve2.setLineCount(0)
                //Mcurve2.draw()
                //Mcurve3.clear() 'curve history
                this.showCurrentCurve();
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        private void Combo1_SelectedIndexChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
            //method1ele = Combo1.Text
            switch (Combo_element.Text)
            {
                case "O":
                    method1ele = "C";
                    break;
                case "N":
                    method1ele = "S";
                    break;
                case "O2":
                    method1ele = "C2";
                    break;
                case "N2":
                    method1ele = "S2";
                    break;
            }
            this.EleChange(method1ele);

        }





        public void recalcArea()
        {
            try
            {
                //user1.method_Renamed = method1.cname
                //user1.methodid = method1.ID
                //Call gDb.myLoadmethodByid((user1.mname), (user1.methodid)) 'use changed  method

                int id = 0;
                double eleArea = 0;
                //DataGridViewRow r = null;
                foreach (DataGridViewRow r in this.DataGrid4.Rows)
                {
                    //r = r_loopVariable;
                    if ((r.Cells["sampleid"].Value != null))
                    {
                        id = (int)r.Cells["sampleid"].Value;
                        if (ModMain.getFrmMain().calcArea(id, method1ele, ref eleArea))
                        {
                            r.Cells["elearea"].Value = eleArea;
                        }
                    }
                }
                //Me.refreshCurvedata()
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        //recalc area
        private void Command10_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            Command10.Enabled = false;
            this.recalcArea();
            Command10.Enabled = true;
        }

        public void getAllMeasuredStand()
        {
            try
            {
                double wlw = 0;
                double w = 0;
                double a = 0;
                int stid = 0;
                int sid = 0;
                foreach (DataGridViewRow r in ModMain.getFrmMain().DataGrid1.Rows)
                {
                    {
                        //treat it
                        if ((int)r.Cells["standardid"].Value != 0)
                        {
                            if (this.notPassCheckChanel(r))
                            {
                            }
                            else
                            {
                                w =(double) r.Cells["weight"].Value;

                                if (System.Convert.IsDBNull(r.Cells["wlweight"].Value))
                                {
                                    wlw = (double)r.Cells["wlweight"].Value;
                                }
                                a = this.getArea(r);
                                stid = (int)r.Cells["standardid"].Value;
                                sid = (int)r.Cells["id"].Value;

                                //gDb.insCurveData(method1.ID, method1ele, stid, w, a, sid, wlw)
                                NCS.curveData d = null;
                                d = new NCS.curveData();
                                d.methodid = ModMain.method1.ID;
                                d.ele = method1ele;
                                d.standardid = stid;
                                d.weight = w;
                                d.eleArea = a;
                                d.sampleid = sid;
                                d.wlweight = wlw;
                                d.quan = 1;
                                d.eleInt = ModMain.gDb.getStandardConc(stid, method1ele);
                                d.curveXishu = ModMain.cxishu;
                                ModMain.cxishu.curveDataList.Add(d);
                                ModMain.getsession().Save(d);
                                ModMain.getsession().Update(ModMain.cxishu);
                                ModMain.getsession().Flush();
                            }
                        }
                    }
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }

        }
        public double getArea(DataGridViewRow r)
        {
            double functionReturnValue = 0;
            {
                switch (method1ele)
                {
                    case "C":
                        functionReturnValue = (double)r.Cells["carea"].Value;
                        break;
                    case "S":
                        functionReturnValue = (double)r.Cells["sarea"].Value;
                        break;
                    case "C2":
                        functionReturnValue = (double)r.Cells["carea"].Value;
                        break;
                    case "S2":
                        functionReturnValue = (double)r.Cells["sarea"].Value;
                        break;
                }
            }
            return functionReturnValue;
        }
        public void calcXishu()
        {
            if (ModMain.cxishu == null)
                return;
            if (ModMain.cxishu.must00)
            {
                add00();
            }
            else 
            {
                del00(method1ele);
            }
            double[] x = null;
            double[] y = null;
            int[] w = null;
            double[] caly = null;
            double[] wl = null;
            int n = 0;
            n = ModMain.cxishu.curveDataList.Count;
            if (n < 2)
            {
                modLog.savelogmsg("no enough point to calc curve xishu");
                return;
            }
            x = new double[n];
            y = new double[n];
            w = new int[n];
            caly = new double[n];
            wl = new double[n];
            int Count = 0;//有效数据个数
            int cishu = 0;
            double stderr = 0;
            double[] xiShu = null;
            double maxx = 0;
            double minx = 0;
            double miny = 0;
            double maxy = 0;
            cishu = 1 + 1;
            foreach (NCS.curveData curvedata in ModMain.cxishu.curveDataList)
            {

                if (curvedata.weight * curvedata.eleInt >= 0)//y>=0
                {
                    if (curvedata.eleArea >= 0)//x>=0
                    {
                        Count = Count + 1;
                        y[Count - 1] = (curvedata.weight * curvedata.eleInt);
                        if (ModMain.buChuCO2 && (ModMain.cxishu.ele == "S" || ModMain.cxishu.ele == "S2"))
                        {
                            double conc = ModMain.gDb.getStandardConc(curvedata.standardid ,"C");//cru, method1ele);
                            x[Count - 1] = curvedata.eleArea-ModMain.cxishu.ln*curvedata.weight*conc;
                        }
                        else
                        {
                            x[Count - 1] = curvedata.eleArea;
                        }
                        if (curvedata.quan > 0)
                        {
                            w[Count - 1] = (int)curvedata.quan;
                        }
                        else
                        {
                            w[Count - 1] = 1;
                        }
                        //记录最大最小
                        if (Count == 1)
                        {
                            minx = x[Count - 1];
                            miny = y[Count - 1];
                            maxx = x[Count - 1];
                            maxy = y[Count - 1];
                        }
                        else
                        {
                            if (minx > x[Count - 1])
                                minx = x[Count - 1];
                            if (miny > y[Count - 1])
                                miny = y[Count - 1];
                            if (maxx < x[Count - 1])
                                maxx = x[Count - 1];
                            if (maxy < y[Count - 1])
                                maxy = y[Count - 1];
                        }
                    }//a>=0

                }//w>0

            }//foreach 
            if (Count < cishu)
            {
                modLog.savelogmsg("not enough points to fit the curve cishu:" + Convert.ToString(Count));
                return;
            }
            xiShu = new double[4];
            //计算系数 0 1 2 3
            Lfit.lfit(x, y, w, Count, ref xiShu, cishu, ref stderr);
            //计算r2
            double yavg = 0;
            double fc = 0;
            int j = 0;
            int i = 0;
            for (i = 0; i <= Count - 1; i++)
            {
                yavg = yavg + y[i];
            }
            yavg = yavg / Count;
            for (i = 0; i <= Count - 1; i++)
            {
                fc = fc + Math.Pow(((y[i] - yavg)), 2F);
            }
            double r2 = 0;
            double jian = 0;
            jian = fc - stderr;
            if (jian < 0)
                jian = 0;
            r2 = ModMain.myDiv(jian, fc);
            minx = minx * 0.95F;
            maxx = maxx * 1.05F;
            //更新曲线系数
            ModMain.cxishu.r = r2;
            ModMain.cxishu.x0 = xiShu[0];
            ModMain.cxishu.x1 = xiShu[1];
            ModMain.cxishu.cmin = minx;
            ModMain.cxishu.cmax = maxx;
            ModMain.cxishu.stderr = stderr;
            this.txtx1.Text = string.Format("{0:F7}", xiShu[1]);
            this.txtx0.Text = string.Format("{0:F7}", xiShu[0]);
            this.TextBoxR2.Text = string.Format("{0:F7}", r2);
            this.Text_up_limit.Text = Convert.ToString(maxx);
            this.Text_low_limit.Text = Convert.ToString(minx);
            this.txtstderr.Text = Convert.ToString(stderr);
            //更新计算浓度
            Count = 0;
            foreach (NCS.curveData curvedata in ModMain.cxishu.curveDataList)
            {

                if (curvedata.weight * curvedata.eleInt >= 0)
                {
                    if (curvedata.eleArea >= 0)
                    {
                        Count = Count + 1;
                        for (j = 0; j <= cishu - 1; j++)
                        {
                            caly[Count - 1] = caly[Count - 1] + Math.Pow(x[Count - 1], j) * xiShu[j];
                        }
                        curvedata.calcconc = caly[Count - 1] / curvedata.weight;
                        curvedata.quan = w[Count - 1];
                    }
                }

            }
            ISession session = ModMain.getsession();
            session.Save(ModMain.cxishu);
            session.Flush();
            this.refreshCurvedata();
            showCurrentCurve();
        }

        public void Command3_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            this.calcXishu();
        }
        public void getId00(ref int id)
        {
            ModMain.gDb.getId00(ref id);
            if (id == 0)
            {
                ModMain.gDb.addstandard00();
                ModMain.gDb.getId00(ref id);
            }
        }

        public void add00()
        {
            //del00(method1ele)
            int id = 0;
            int stid = 0;
            if (ModMain.gDb.getId00(ref id))
            {
            }
            else
            {
                ModMain.gDb.addstandard00();
                ModMain.gDb.getId00(ref id);
            }
            NCS.curveData curvedata = null;
            bool find = false;
            find = false;
            foreach (NCS.curveData tcurvedata in ModMain.cxishu.curveDataList)
            {
                if (tcurvedata.standardid == stid & tcurvedata.quan == 10000)
                {
                    find = true;
                    break; // TODO: might not be correct. Was : Exit For
                }
            }
            if (!find)
            {
                double blank = 0;
                blank = ModMain.cxishu.blankarea;
                curvedata = new NCS.curveData();
                {
                    curvedata.methodid = ModMain.method1.ID;
                    curvedata.standardid = (int)stid;
                    curvedata.quan = 10000;
                    curvedata.ele = method1ele;
                    curvedata.weight = 0.5F;
                    curvedata.eleArea = blank;
                }
                curvedata.curveXishu = ModMain.cxishu;
                ModMain.cxishu.curveDataList.Add(curvedata);
                ModMain.getsession().Save(ModMain.cxishu);
                ModMain.getsession().Flush();
            }
            //refreshCurvedata()
        }
        public void del00(string method1ele)
        {
            NCS.curveData todel = null;
            foreach (NCS.curveData curvedata in ModMain.cxishu.curveDataList)
            {
                if (curvedata.eleInt == 0)
                {
                    todel = curvedata;
                    break; // TODO: might not be correct. Was : Exit For
                }
            }
            if ((todel != null))
            {
                ModMain.cxishu.curveDataList.Remove(todel);
                ModMain.getsession().Delete(todel);
                ModMain.getsession().Flush();
                this.refreshCurvedata();
            }
        }

        public void showCurrentCurve()
        {
            mcurve1.setTwoLine();
            //mcurve1.setshowpoint(True)
            mcurve1.setxyDw("vs", "cg");
            int i = 0;
            double[] x = null;
            double[] y = null;
            int[] w = null;
            double[] caly = null;
            double[] wl = null;
            int n = 0;
            n = ModMain.cxishu.curveDataList.Count;

            if (n < 2)
            {
                modLog.savelogmsg("no enough point to show curve"); return;
            }
            x = new double[n + 1];
            y = new double[n + 1];
            w = new int[n + 1];
            wl = new double[n + 1];
            int Count = 0;
            int cishu = 0;
            //Dim stderr As double
            double[] xiShu = null;
            double maxx = 0;
            double minx = 0;
            double miny = 0;
            double maxy = 0;
            //error no dataset
            double blank = 0;
            blank = ModMain.cxishu.blankarea;
            cishu = 1 + 1;
            //NCS.curveData data1 = null;
            foreach (NCS.curveData data1 in ModMain.cxishu.curveDataList)
            {
                //data1 = data1_loopVariable;
                {
                    if (data1.weight * data1.eleInt >= 0)
                    {
                        if (data1.eleArea >= 0)
                        {
                            Count = Count + 1;
                            y[Count - 1] = (data1.eleInt * data1.weight);
                            if (ModMain.buChuCO2 && (ModMain.cxishu.ele == "S" || ModMain.cxishu.ele == "S2"))
                            {
                                double conc = ModMain.gDb.getStandardConc(data1.standardid, "C");//cru, method1ele);
                                x[Count - 1] = data1.eleArea - ModMain.cxishu.ln * data1.weight * conc;
                            }
                            else
                            {
                                x[Count - 1] = data1.eleArea;
                            }
                            if (data1.quan < 1)
                            {
                                w[Count - 1] = (int)data1.quan;
                            }
                            else
                            {
                                w[Count - 1] = (int)data1.quan;
                            }
                            if (Count == 1)
                            {
                                minx = x[Count - 1];
                                miny = y[Count - 1];
                                maxx = x[Count - 1];
                                maxy = y[Count - 1];
                            }
                            else
                            {
                                if (minx > x[Count - 1])
                                    minx = x[Count - 1];
                                if (miny > y[Count - 1])
                                    miny = y[Count - 1];
                                if (maxx < x[Count - 1])
                                    maxx = x[Count - 1];
                                if (maxy < y[Count - 1])
                                    maxy = y[Count - 1];
                            }
                        }
                    }
                }

            }

            if (Count < cishu)
            {
                modLog.savelogmsg("not enough points to fit cishu:" + Convert.ToString(Count));
                return;
            }
            xiShu = new double[4];
            //0 1 2 3
            xiShu[0] = ModMain.cxishu.x0;
            xiShu[1] = ModMain.cxishu.x1;
            //showCurve
            int j = 0;
            double[] calcx = new double[101];
            caly = new double[101];
            //Dim i As Integer
            double tmp = 0;
            tmp = minx;
            minx = minx - (maxx - minx) * 0.1F;
            maxx = maxx + (maxx - tmp) * 0.1F;
            for (i = 0; i <= 100 - 1; i++)
            {
                calcx[i] = minx + i * (maxx - minx) / 100;
                caly[i] = 0;
                //
                for (j = 0; j <= cishu - 1; j++)
                {
                    caly[i] = caly[i] + Math.Pow(calcx[i], j) * xiShu[j];
                }
            }

            mcurve1.setArrV(ref x, ref y, Count, 0);
            mcurve1.setArrV(ref calcx, ref caly, 100, 1);
            //must sort
            mcurve1.fit();
        }
        public int getEleChanel(ref string method1ele)
        {
            int functionReturnValue = 0;
            switch (method1ele)
            {
                case "C":
                    functionReturnValue = 0;
                    break;
                case "C2":
                    functionReturnValue = 2;
                    break;
                case "S":
                    functionReturnValue = 1;
                    break;
                case "S2":
                    functionReturnValue = 3;
                    break;
            }
            return functionReturnValue;
        }
        public void delAllCur()
        {
            System.Collections.Generic.List<NCS.curveData> l = new System.Collections.Generic.List<NCS.curveData>();
            foreach (NCS.curveData d in ModMain.cxishu.curveDataList)
            {
                l.Add(d);
            }
            ModMain.cxishu.curveDataList.Clear();
            foreach (NCS.curveData d in l)
            {
                ModMain.getsession().Delete(d);
            }
            ModMain.getsession().Save(ModMain.cxishu);
            ModMain.getsession().Flush();
        }
        private void Command6_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            Command6.Enabled = false;
            this.delAllCur();
            this.refreshCurvedata();
            Command6.Enabled = true;
        }

        public bool notPassCheckChanel(DataGridViewRow r)
        {
            bool functionReturnValue = false;
            {
                switch (method1ele)
                {
                    case "C":
                        if ((int)r.Cells["ishc"].Value == -1)
                        {
                            modLog.savelogmsg("not LC");
                            functionReturnValue = true;
                        }
                        break;
                    case "S":
                        if ((int)r.Cells["ishs"].Value == -1)
                        {
                            modLog.savelogmsg("not LS");
                            functionReturnValue = true;
                        }
                        break;
                    case "C2":
                        if ((int)r.Cells["ishc"].Value == 0)
                        {
                            modLog.savelogmsg("not HC");
                            functionReturnValue = true;
                        }
                        break;
                    case "S2":
                        if ((int)r.Cells["ishs"].Value == 0)
                        {
                            modLog.savelogmsg("not HS");
                            functionReturnValue = true;
                        }
                        break;
                }
            }
            return functionReturnValue;
        }

        private void Command8_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            Command8.Enabled = false;
            try
            {
                NCS.curveData id = null;
                id = (NCS.curveData)this.DataGrid4.CurrentRow.DataBoundItem;
                ModMain.cxishu.curveDataList.Remove(id);
                ModMain.getsession().Delete(id);

                ModMain.getsession().Flush();
                refreshCurvedata();
            }
            catch (Exception e1)
            {
                modLog.savelogmsg(e1.ToString());
            }
            Command8.Enabled = true;
        }


        public void exit_Renamed_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            
            this.Close();
        }


        private void FrmMethod_Load(System.Object eventSender, System.EventArgs eventArgs)
        {
            //beforeUse = -1
            ModMain.getFrmResult().Visible = true;
            SSTab_curve.SelectedIndex = 0;
            ModMain.makemethod = true;
            this.displayMethod();
            refreshMethod();
            modLog.savelogmsg("end frmMethod load");
        }



        private void FrmMethod_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
        {
            ModMain.getsession().Flush();
            ModMain.makemethod = false;
            ModMain.getFrmMain().FromMethodReturn();
            //ModMain.getFrmMethod() = null;
        }

        public void mnuChangeLineXishu_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {
                double v = 0;
                if (ModMain.checkuser())
                {
                    MyInputBox mbox = new MyInputBox("新线性化系数", Text_lineable.Text);
                    mbox.ShowDialog();
                    v = Convert.ToSingle(mbox.s);
                    //gdb.rscurveXishu.Fields("LINExishu").Value = v
                    ModMain.cxishu.LINExishu = v;
                    //  Text4.Enabled = True
                    Text_lineable.Text = Convert.ToString(v);
                    ModMain.getsession().Flush();
                    //  Text4.Enabled = False
                }
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void mnuCopyMethod_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            try
            {
                //int nid = 0;
                string sname = null;
                MyInputBox mbox = new MyInputBox("新方法的名称");
                mbox.ShowDialog();
                sname = mbox.s;
                if (string.IsNullOrEmpty(sname))
                    return;
                //ModMain.gDb.copyMethod(ModMain.method1.ID, ref nid, sname);
                //ModMain.user1.methodid = nid;
                //ModMain.gDb.myLoadmethodByid(ModMain.user1.mname, ModMain.user1.methodid);
                ISession session = ModMain.getsession();
                NCS.method m1 = (NCS.method)ModMain.method1.Clone();
                m1.cname = sname;
                session.Save(m1);
                session.Flush();
                //foreach (NCS.curveXishu x in m1.curveXishuList)
                //{
                //    x.methodid = m1.ID;
                //    session.Save(x);
                //    foreach (NCS.curveData d in x.curveDataList)
                //    {
                //        d.methodid = m1.ID;
                //        session.Save(d);
                //    }
                //}
                //session.Flush();
                ModMain.method1 = m1;
                refreshMethod();
                this.displayMethod();
                return;
            }
            catch (System.Exception e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }
        public void deleteXishuToolStripMenuItem_Click(System.Object eventSender, System.EventArgs eventArgs)
        { 
        }
        public void mnuDelete_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //If Not checkUpdate() Then Exit Sub
            FrmLoadmethod fm = new FrmLoadmethod();
            fm.mconfirm = false;
            fm.ShowDialog();
            //Dim a As int
            if (fm.mconfirm)
            {
                //DialogResult r = MessageBox.Show("是否确实要删除该方法?", "");
                DialogResult r = MessageBox.Show(this, "是否确实要删除该方法?", "", MessageBoxButtons.YesNo);
                if (r == DialogResult.Yes )
                {
                    //if ((ModMain.method1 != null))
                    //{
                        if (ModMain.method1.ID == fm.methodid)
                        {
                            MessageBox.Show("不能删除当前方法！");
                        }
                        else
                        {
                            //ModMain.gDb.deleteMethodByid((fm.methodid));
                            NCS.method m;
                            ISession session=ModMain.getsession();
                            m =(NCS.method ) session.Get(typeof(NCS.method), fm.methodid);
                            session.Delete(m);
                            session.Flush();
                        }

                    //}
                    //else
                    //{
                    //    ModMain.gDb.deleteMethodByid((fm.methodid));
                    //    //Dim m As NCS.method
                    //    //m = session.Get(GetType(NCS.method), FrmLoadmethod.methodid)
                    //    //session.Delete(m)
                    //    //session.Flush()
                    //}

                }
            }
        }

        public void mnuLine_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            if (ModMain.checkuser())
            {
                ModMain.gDb.myLoadmethodByid((ModMain.user1.mname), (ModMain.user1.methodid));
                frmLine fm = new frmLine();
                fm.ShowDialog();
            }
        }

        public void mnuLoad_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //If Not checkUpdate() Then Exit Sub
            FrmLoadmethod fm = new FrmLoadmethod();
            fm.ShowDialog();
            if (fm.mconfirm)
            {
                //user1.method_Renamed = FrmLoadmethod.methodname
                ModMain.user1.methodid = fm.methodid;
                ModMain.gDb.myLoadmethodByid((ModMain.user1.mname), (ModMain.user1.methodid));
                ModMain.gDb.saveUser(ref ModMain.user1);
                refreshMethod();
                //show method to form
                this.displayMethod();
                Frame2.Enabled = true;
                SSTab_curve.Enabled = true;
            }

        }

        public void mnuLog_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            modLog.showLog();
        }

        public void mnuNew_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            //newMakemethod();
        }

        //Public Sub mnuRefresh_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
        //    Dim Index As int = mnuRefresh.GetIndex(eventSender)
        //    Me.showCurrentCurve()
        //End Sub


        public void mnuShow_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            modLog.showLog();
        }

        public void refreshCurvedata()
        {
            if (ModMain.cxishu == null)
                return;
            //Me.DataGrid4.DataBindings.Clear()
            //Me.DataGrid4.DataBindings.Add (New System.Windows.Forms.Binding("datasourve",cxishu,"curveDatalist")
            //Dim b As BindingSource
            //b = New BindingSource(
            System.ComponentModel.Container Mecomponents = new System.ComponentModel.Container();
            System.Windows.Forms.BindingSource MeMuserBindingSource = new System.Windows.Forms.BindingSource(Mecomponents);
            MeMuserBindingSource.DataSource = typeof(NCS.curveData);
            foreach (NCS.curveData o in ModMain.cxishu.curveDataList)
            {
                MeMuserBindingSource.Add(o);
            }
            this.DataGrid4.DataSource = null;
            this.DataGrid4.DataSource = MeMuserBindingSource;
            //cxishu.curveDataList
            if (ModMain.cxishu.curveDataList.Count < 1)
                return;
            DataGrid4.Columns["curveXishu"].Visible = false;
            DataGrid4.Columns["methodid"].Visible = false;
            DataGrid4.Columns["curvexishuid"].Visible = false;
            DataGrid4.Columns["sampleid"].Visible = false;
            //sampleid
            DataGrid4.Columns["standardid"].HeaderText = "标样编号";

            DataGrid4.Columns["eleArea"].HeaderText = "面积";
            DataGrid4.Columns["eleArea"].DefaultCellStyle.Format = "0.00";

            DataGrid4.Columns["eleInt"].HeaderText = "含量";
            DataGrid4.Columns["eleInt"].DefaultCellStyle.Format = "0.00000";

            DataGrid4.Columns["weight"].HeaderText = "质量";
            DataGrid4.Columns["weight"].DefaultCellStyle.Format = "0.0000";
            //weight
            DataGrid4.Columns["ele"].Visible = false;
            //ele
            DataGrid4.Columns["calcconc"].HeaderText = "计算含量";
            DataGrid4.Columns["calcconc"].DefaultCellStyle.Format = "0.00000";
            //calcconc
            DataGrid4.Columns["wlweight"].HeaderText = "助熔剂质量";
            DataGrid4.Columns["wlweight"].DefaultCellStyle.Format = "0.0000";
            //wlweight
            DataGrid4.Columns["quan"].HeaderText = "权重";
            //quan
        }
        public void refreshPowerSet()
        {
            if (ModMain.method1 == null)
                return;
            try
            {
                if (ModMain.method1.powerList.Count < 1)
                {
                    NCS.powerSet d = new NCS.powerSet();
                    d.begin_power = 4000;
                    d.end_power = 3800;
                    d.time = 25;
                    d.method = ModMain.method1;
                    d.sn = 1;
                    ModMain.method1.powerList.Add(d);
                    ModMain.getsession().Save(d);
                    ModMain.getsession().Update(ModMain.method1);
                    ModMain.getsession().Flush();
                }
                System.ComponentModel.Container Mecomponents = new System.ComponentModel.Container();
                System.Windows.Forms.BindingSource MeMuserBindingSource = new System.Windows.Forms.BindingSource(Mecomponents);
                MeMuserBindingSource.DataSource = typeof(NCS.powerSet);
                foreach (NCS.powerSet o in ModMain.method1.powerList)
                {
                    MeMuserBindingSource.Add(o);
                }
                this.DataGridView_powerSet.DataSource = null;
                this.DataGridView_powerSet.DataSource = MeMuserBindingSource;
                //cxishu.curveDataList

                DataGridView_powerSet.Columns["method"].Visible = false;
                DataGridView_powerSet.Columns["id"].Visible = false;
                DataGridView_powerSet.Columns["begin_power"].HeaderText = "开始功率";
                DataGridView_powerSet.Columns["end_power"].HeaderText = "结束功率";
                DataGridView_powerSet.Columns["time"].HeaderText = "时间";
                DataGridView_powerSet.Columns["sn"].HeaderText = "序号";
            }
            catch (System.Data.OleDb.OleDbException e)
            {
                modLog.savelogmsg(e.ToString());
            }
        }

        public void refreshMethod()
        {
            //= session.Get(GetType(NCS.method), pk)
            if (ModMain.method1 == null)
            {
                this.Frame2.Enabled = false;
                this.Combo_element.Enabled = false;
                this.SSTab_curve.Enabled = false;
            }
            else
            {
                this.Frame2.Enabled = true;
                this.Combo_element.Enabled = true;
                this.SSTab_curve.Enabled = true;
                refreshPowerSet();
                this.Text_o_swtich.DataBindings.Clear();
                this.Text_o_swtich.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "cswitch"));
                this.TextBox_dengdaitime.DataBindings.Clear();
                this.TextBox_dengdaitime.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "dengdaitime"));
                this.TextBox_tuoqiPower.DataBindings.Clear();
                this.TextBox_tuoqiPower.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "tuoqipower"));
                this.TextBox_chongxiPower.DataBindings.Clear();
                this.TextBox_chongxiPower.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "chongxi_power"));
                this.TextBox_dengdai_power.DataBindings.Clear();
                this.TextBox_dengdai_power.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "dengdai_power"));
                this.TextBox_sample_delay.DataBindings.Clear();
                this.TextBox_sample_delay.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "sample_delay"));

                //ModMain.rebind(Text1, "Text", ModMain.method1, "cswitch");
                //ModMain.rebind(this.TextBox_dengdaitime, "Text", ModMain.method1, "dengdaitime");
                //ModMain.rebind(this.TextBox_tuoqiPower, "Text", ModMain.method1, "tuoqipower");
                //ModMain.rebind(this.TextBox_chongxiPower, "Text", ModMain.method1, "chongxi_power");
                //ModMain.rebind(this.TextBox_dengdai_power, "Text", ModMain.method1, "dengdai_power");
                //ModMain.rebind(this.TextBox_sample_delay, "Text", ModMain.method1, "sample_delay");
                this.Text_n_switch.DataBindings.Clear();
                this.Text_n_switch.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "sswitch"));
                this.Text_method_name.DataBindings.Clear();
                this.Text_method_name.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "cname"));
                this.Text_smooth_num.DataBindings.Clear();
                this.Text_smooth_num.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "smoothnum"));
                this.Text_sample_time.DataBindings.Clear();
                this.Text_sample_time.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "sampletime"));
                this.Text_flush_time.DataBindings.Clear();
                this.Text_flush_time.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "flushtime"));
                this.txtPowertime.DataBindings.Clear();
                this.txtPowertime.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "tuoqitime"));
                this.txtwlc.DataBindings.Clear();
                this.txtwlc.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "wlC"));
                this.txtwls.DataBindings.Clear();
                this.txtwls.DataBindings.Add(new System.Windows.Forms.Binding("Text", ModMain.method1, "wlS"));
                this.ckJieqi.DataBindings.Clear();
                this.ckJieqi.DataBindings.Add(new System.Windows.Forms.Binding("Checked", ModMain.method1, "jieqi"));

                //ModMain.rebind(Text2, "Text", ModMain.method1, "sswitch");
                //ModMain.rebind(Text3, "Text", ModMain.method1, "cname");
                ////Call rebind(Label10, "Text", method1, "cuser")
                //ModMain.rebind(Text5, "Text", ModMain.method1, "smoothnum");
                //ModMain.rebind(Text6, "Text", ModMain.method1, "sampletime");
                //ModMain.rebind(Text7, "Text", ModMain.method1, "flushtime");
                ////new add
                //ModMain.rebind(txtPowertime, "Text", ModMain.method1, "tuoqitime");
                //ModMain.rebind(txtwlc, "Text", ModMain.method1, "wlC");
                //ModMain.rebind(txtwls, "Text", ModMain.method1, "wlS");
                //ModMain.rebind(ref this.ckJieqi, "Checked", ref ModMain.method1, "jieqi");
                Combo_element.Items.Clear();
                if (ModMain.getChanelEnable("C"))
                {
                    Combo_element.Items.Add("O");
                }
                if (ModMain.getChanelEnable("S"))
                {
                    Combo_element.Items.Add("N");
                }
                if (ModMain.getChanelEnable("C2"))
                {
                    Combo_element.Items.Add("O2");
                }
                if (ModMain.getChanelEnable("S2"))
                {
                    Combo_element.Items.Add("N2");
                }
                Combo_element.SelectedIndex = 0;
            }
        }


        public void displayMethod()
        {
            string s = null;
            s = "";
            if ((ModMain.method1 != null))
                s = ModMain.method1.cname;
            //methodStatus.Text = "用户:" + user1.mname + ",方法:" + s
        }

        public void caliAll()
        {
            caliChanel("C");
            caliChanel("S");
            caliChanel("C2");
            caliChanel("S2");
        }
        public void caliChanel(string s)
        {
            if (ModMain.getChanelEnable(s))
            {
                Combo_element.Text = s;
                this.EleChange(s);
                this.delAllCur();
                this.getAllMeasuredStand();
                this.refreshCurvedata();
                this.calcXishu();
            }

        }

        private void DataGrid4_DataError(object sender, System.Windows.Forms.DataGridViewDataErrorEventArgs e)
        {
            modLog.savelogmsg(e.ToString());
        }

        private void DataGrid4_RowEnter(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            Debug.Print("error here");
        }

        private void DataGridView_powerSet_UserAddedRow(object sender, System.Windows.Forms.DataGridViewRowEventArgs e)
        {

            System.Windows.Forms.BindingSource s = DataGridView_powerSet.DataSource as System.Windows.Forms.BindingSource;
            NCS.powerSet p = (NCS.powerSet)s.Current;// as NCS.powerSet;
            p.method = ModMain.method1;
            ModMain.method1.powerList.Add(p);
            ModMain.getsession().Save(p);
            ModMain.getsession().Update(ModMain.method1);
            ModMain.getsession().Flush();
        }

        private void DataGridView_powerSet_UserDeletingRow(object sender, System.Windows.Forms.DataGridViewRowCancelEventArgs e)
        {
            System.Windows.Forms.BindingSource s = DataGridView_powerSet.DataSource as System.Windows.Forms.BindingSource;
            NCS.powerSet p = (NCS.powerSet)s.Current;//() as NCS.powerSet;
            //session.Delete(p)
            //session.Update(method1)
            ModMain.method1.powerList.Remove(p);
            ModMain.getsession().Delete(p);
            ModMain.getsession().Flush();
        }

        private void mnuSave_Click(object sender, EventArgs e)
        {
            //FormHtmlEditorMethod fm = new FormHtmlEditorMethod();
            //fm.ShowDialog();
        }

        private void test1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (ModMain.method1.curveXishuList.Count > ModMain.NUMChanel)
            //{
            //    ISession s = ModMain.getsession();
            //    while (ModMain.method1.curveXishuList.Count > ModMain.NUMChanel)
            //    {
            //        NCS.curveXishu x = ModMain.method1.curveXishuList[ModMain.method1.curveXishuList.Count - 1];
            //        ModMain.method1.curveXishuList.Remove(x);
            //        x.method = null;
            //        s.Delete(x);
            //    }
            //    s.Flush();
            //}
            //else
            //{
            //}
        }

        private void MainMenu1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void txtstderr_TextChanged(object sender, EventArgs e)
        {

        }

  
    }
}
